package com.k12.admim.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.k12.admim.model.entity.sys.SysRole;
import com.k12.admim.model.entity.sys.SysRoleDept;
import com.k12.admim.model.entity.sys.SysUser;
import com.k12.admim.model.entity.sys.SysUserRole;
import com.k12.admim.model.vo.sys.SysRoleMenuVo;
import com.k12.admim.model.vo.sys.SysRoleVo;
import com.k12.admim.model.vo.sys.SysUserVo;
import com.k12.admim.rpc.UserFeignClient;
import com.k12.admim.service.OperatorRoleService;
import com.k12.admim.utils.RequestContextUtil;
import com.k12.common.model.resp.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class OperatorRoleServiceImpl implements OperatorRoleService{

    @Resource
    private UserFeignClient userFeignClient;

    @Override
    public R insertRole(SysRoleVo sysRoleVo) {
        Long loginId = (Long) StpUtil.getLoginId();
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        String message = userFeignClient.checkRole(sysRoleVo);
        if ("".equals(message)){
            sysRoleVo.setCreateBy(loginId.toString());
            sysRoleVo.setTenantId(Long.parseLong(tenantId));
            userFeignClient.addRole(sysRoleVo);
            insertRoleMenu(sysRoleVo);

            return R.success();
        }else{
            return R.failed( message);
        }
    }

    @Override
    public List<SysRole> selectRoleList(SysRoleVo sysRoleVo) {
        return userFeignClient.selectSysRoleList(sysRoleVo);
    }

    @Override
    public void checkRoleDataScope(Long roleId,String tenantId) {
        SysRole sysRole = userFeignClient.selectOneRole(roleId,tenantId);
        if (sysRole == null){
            throw new RuntimeException("角色不存在");
        }
    }

    @Override
    public SysRole selectRoleById(Long roleId, String tenantId) {
        return userFeignClient.selectOneRole(roleId, tenantId);
    }

    @Override
    public R deleteRoleIds(String tenantId, String loginId, Long[] roleIds) {
        for (Long roleId : roleIds)
        {
            if ("1".equals(loginId)){
                return R.failed("不允许删除超级管理员角色");
            }
            SysRole sysRole = userFeignClient.selectOneRole(roleId,tenantId);
            if (sysRole == null){
                return R.failed("角色不存在");
            }
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setTenantId(Long.valueOf(tenantId));
            List<SysUserRole> sysUserRoleList = userFeignClient.getAllUserRole(sysUserRole);
            if (sysUserRoleList.size() > 0)
            {
                return R.failed(String.format("%1$s已分配,不能删除", sysRole.getRoleName()));
            }
        }
        // 删除角色与菜单关联
        userFeignClient.deleteRoleMenu(roleIds,tenantId);
        // 删除角色与部门关联
        userFeignClient.deleteRoleDeptByIds(roleIds,tenantId);
        userFeignClient.deleteRoleByIds(roleIds,tenantId);
        return R.success();
    }

    @Override
    public R authDataScope(SysRole role) {
        String loginId = StpUtil.getLoginId().toString();
        String tenantId = RequestContextUtil.getTenantId();
        if(StringUtils.isBlank(tenantId)){
            return R.failed("非法登录");
        }
        role.setTenantId(Long.valueOf(tenantId));
        if ("1".equals(loginId)){
            return R.failed("不允许删除超级管理员角色");
        }
        SysRole sysRole = userFeignClient.selectOneRole(role.getRoleId(),tenantId);
        if (sysRole == null){
            throw new RuntimeException("角色不存在");
        }
        userFeignClient.updateRole(role);
        userFeignClient.deleteRoleDeptById(role.getRoleId(),tenantId);
        userFeignClient.updateRole(role);
        userFeignClient.deleteRoleDeptById(role.getRoleId(),tenantId);
        insertRoleDept(role);
        return R.success();
    }

    @Override
    public List<SysUser> allocatedList(SysUserVo userVo) {
        return userFeignClient.selectAllocatedList(userVo);
    }

    @Override
    public int insertAuthUsers(Long roleId, Long[] userIds,String tenantId) {
        // 新增用户与角色管理
        List<SysUserRole> list = new ArrayList<SysUserRole>();
        for (Long userId : userIds)
        {
            SysUserRole ur = new SysUserRole();
            ur.setUserId(userId);
            ur.setRoleId(roleId);
            ur.setTenantId(Long.valueOf(tenantId));
            list.add(ur);
        }
        return userFeignClient.saveSysUserRole(list);
    }

    public Integer insertRoleDept(SysRole role)
    {
        int rows = 1;
        // 新增角色与部门（数据权限）管理
        List<SysRoleDept> list = new ArrayList<SysRoleDept>();
        for (Long deptId : role.getDeptIds())
        {
            SysRoleDept rd = new SysRoleDept();
            rd.setRoleId(role.getRoleId());
            rd.setDeptId(deptId);
            rd.setTenantId(role.getTenantId());
            list.add(rd);
        }
        if (list.size() > 0)
        {
            rows = userFeignClient.insertRoleDeptList(list);
        }
        return rows;
    }


    private void insertRoleMenu(SysRoleVo sysRoleVo) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenuVo> list = new ArrayList<SysRoleMenuVo>();
        for (Long menuId : sysRoleVo.getMenuIds())
        {
            SysRoleMenuVo rm = new SysRoleMenuVo();
            rm.setRoleId(sysRoleVo.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        userFeignClient.addMenuRole(list);
    }
}
